<template>
  <el-dialog
    :title="!dataForm.userId ? '新增电影管理员' : '修改电影管理员信息'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="电影院名字" prop="userName">
        <el-input v-model="dataForm.realName" placeholder="电影院名字"></el-input>
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.password"
          type="password"
          placeholder="密码"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="comfirmPassword"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.comfirmPassword"
          type="password"
          placeholder="确认密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
  <el-form-item label="地址" prop="specificAddr">

        <el-row>
          <el-col :span="12">
            <el-form-item prop="operateId">
              <el-select clearable v-model="formData.proId" @change="proChange">
                <el-option
                  v-for="item in proList"
                  :key="item.proId"
                  :label="item.proName"
                  :value="item.proId"
                >
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="operateId">
              <el-select
                clearable
                v-model="formData.cityId"
                @change="cityChange"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.cityId"
                  :label="item.cityName"
                  :value="item.cityId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="operateId">
              <el-select clearable v-model="formData.dirId" @change="dirChange">
                <el-option
                  v-for="item in dirList"
                  :key="item.disId"
                  :label="item.disName"
                  :value="item.disId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
                <el-input v-model="dataForm.specificAddr" placeholder="请填写具体地址(乡,镇,街道,门牌)"></el-input>

      </el-form-item>      </el-form-item>
      <el-form-item label="退票状态" prop="endorse">
        <el-switch
          style="display: block"
          v-model="dataForm.endorse"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="可以退"
          inactive-text="不可以"
          :active-value="0"
  :inactive-value="1"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="改签状态" prop="allowRefund">
        <el-switch
          style="display: block"
          v-model="dataForm.allowRefund"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="可以退"
          inactive-text="不可以"
          :active-value="0"
  :inactive-value="1"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="屏幕类型" prop="hallType">
        <el-input v-model="dataForm.hallType" placeholder="屏幕类型"></el-input>
      </el-form-item>
      <el-form-item label="是否有小吃" size="mini" prop="snack">
        <el-switch
          style="display: block"
          v-model="dataForm.snack"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="允许"
          inactive-text="禁止"
          :active-value="0"
  :inactive-value="1"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="可播电影" prop="moviesList">
        <el-button type="primary" @click="slotAppend">选择</el-button>
        <el-table :data="dataForm.moviesList">
          <el-table-column
            property="chName"
            label="中文名"
            width="150"
          ></el-table-column>
        </el-table>
      </el-form-item>
      <el-dialog
        width="30%"
        title="内层 Dialog"
        :visible.sync="innerVisible"
        append-to-body
      >
        <el-table
          ref="multipleTable"
          :data="allMovies"
          @selection-change="selectionChangeHandle"
        >
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50"
          ></el-table-column>
          <el-table-column
            property="chName"
            label="中文名"
            width="150"
          ></el-table-column>
        </el-table>
     <el-button type="primary" @click="modfiyMovies">确定</el-button>
      </el-dialog>
      <el-form-item label="状态" size="mini" prop="status">
        <el-switch
          style="display: block"
          v-model="dataForm.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="活跃"
          inactive-text="禁用"
          :active-value="1"
  :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    };
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("确认密码不能为空"));
      } else if (this.dataForm.password !== value) {
        callback(new Error("确认密码与密码输入不一致"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      d: '',
      c: '',
      p: '',
        cityList: [],
      dirList: [],
      proList: [],
      formData: {proId:"",dirId:"",cityId: ""},
      dataListSelections: [],
      allMovies: [],
      innerVisible: false,
      visible: false,
      roleList: [],
      dataForm: {
        id: 0,
        userName: "",
        password: "",
        comfirmPassword: "",
        salt: "",
        email: "",
        mobile: "",
        roleIdList: [],
        status: 1,
       specificAddr: "",
       moviesList: '',
       
      },
      dataRule: {
        // userName: [
        //   { required: true, message: "用户名不能为空", trigger: "blur" },
        // ],
        // password: [{ validator: validatePassword, trigger: "blur" }],
        // comfirmPassword: [
        //   { validator: validateComfirmPassword, trigger: "blur" },
        // ],
        // email: [
        //   { required: true, message: "邮箱不能为空", trigger: "blur" },
        //   { validator: validateEmail, trigger: "blur" },
        // ],
        // mobile: [
        //   { required: true, message: "手机号不能为空", trigger: "blur" },
        //   { validator: validateMobile, trigger: "blur" },
        // ],
      },
    };
  },
  watch: {
    "formData.proId": function (val) { 
        this.formData.proId=val;
    if(!this.addVar){
      this.formData.dirId = "";
        this.formData.cityId = "";
    }
          
   
      console.log("pro:"+this.formData.proId)
    },
    "formData.cityId": function (val) {
     if(!this.addVar){
        this.formData.dirId = "";
     }
      this.formData.cityId=val;
      console.log("city:"+this.formData.cityId)
    },
    "formData.dirId": function (val) {
      this.addVar=false
       this.formData.dirId=val;
      this.dataForm.address = val;
      console.log("dir:"+this.dataForm.address)
    },
  },
  methods: {
    beforeClose(){
       this.formData={};
    },
    getProList() {
      this.$http({
        url: this.$http.adornUrl(`/area/tprovince/list/100000`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.proList = data.dataList;
        console.log(data);
      });
    },
    getCityList() {
      this.$http({
        url: this.$http.adornUrl(`/area/tcity/list/` + this.formData.proId),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.cityList = data.dataList;
        console.log("city",data);
      });
    },
    getDirList() {
      this.$http({
        url: this.$http.adornUrl(
          `/area/tdistrict/list/` + this.formData.cityId
        ),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.dirList = data.dataList;
        console.log(data);
      });
    },
    // 操作人选中项发生变化
    proChange(val) {
      console.log("pro操作", val);
      if (val) {
        let obj = {};
        // obj = this.operateOption.find(item => {
        //   //这里的operateOption就是上面遍历的数据源
        //   return item.value === val //筛选出匹配数据
        // })

        this.$set(this.formData, this.formData.proId, val);
        this.cityList = [];
        this.dirList = [];
        this.getCityList();
        // console.log('修改操作人名称', obj.label, obj.value)
      } else {
        this.$set(this.formData, this.formData.proId, "");
      }
    },
    dirChange(val) {
      console.log("dir操作", val);
      if (val) {
        let obj = {};
        // obj = this.operateOption.find(item => {
        //   //这里的operateOption就是上面遍历的数据源
        //   return item.value === val //筛选出匹配数据
        // })

        this.$set(this.formData, this.formData.dirId, val);
        // console.log('修改操作人名称', obj.label, obj.value)
      } else {
        this.$set(this.formData, this.formData.dirId, "");
      }
    },
    // 操作人选中项发生变化
    cityChange(val) {
      console.log("city操作", val);
      if (val) {
        let obj = {};
        // obj = this.operateOption.find(item => {
        //   //这里的operateOption就是上面遍历的数据源
        //   return item.value === val //筛选出匹配数据
        // })

        this.$set(this.formData, this.formData.cityId, val);
        this.dirList = [];
        this.getDirList();
        //清空
        // this.formData.operateName = obj.label
        // console.log('修改操作人名称', obj.label, obj.value)
      } else {
        // this.formData.operateName = ''
              console.log("city操作空");
        this.$set(this.formData, this.formData.cityId, "");
      }
    },
    init(id) {
        this.getProList();
      this.dataForm.userId = id || 0;

      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
      this.allMovies=[];
      this.formData={proId:"",dirId:"",cityId: ""};
      this.$http({
        url: this.$http.adornUrl(`/cb/movie/list/up`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.allMovies = data.page.list;
        }
      });
      if (this.dataForm.userId) {
        this.$http({
          url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.userId}`),
          method: "get",
          params: this.$http.adornParams(),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            console.log(data.user);
            this.dataForm = data.user;
            this.dataForm.password = "";
            this.dataForm.comfirmPassword = "";

            this.getAddrs();
          }
        });
      }
    },
      getAddrs(){
       this.$http({
            url: this.$http.adornUrl('/area/tdistrict/addr/'+this.dataForm.address),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.addVar=true;
              // console.log(data)
              this.getProList();
              console.log("1",data.addrs[0])
              this.formData.proId=data.addrs[0];
              this.getCityList();               
              console.log("2",data.addrs[1])

              this.formData.cityId=data.addrs[1];
              this.getDirList();
               console.log("3",data.addrs[2])
              this.formData.dirId=data.addrs[2];
            }
          });
    },
    modfiyMovies(){    
        this.innerVisible = false;

      this.dataForm.moviesList=this.dataListSelections
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
      this.dataForm.movies = "";
      if (this.dataListSelections) {
        this.dataListSelections.forEach((row) => {
          this.dataForm.movies += row.id + ",";
        });

        this.dataForm.movies = this.dataForm.movies.substring(
          0,
          this.dataForm.movies.length - 1
        );
      }
      console.log(this.dataForm.movies);
    },
    // 嵌套对话框
    slotAppend() {
      this.innerVisible = true;
      this.toggleSelection();
    },
    // 选择有的电影
    toggleSelection() {
      if(this.dataForm.moviesList&& this.allMovies){
        this.$nextTick(() => {
        this.dataForm.moviesList.forEach((row) => {
          this.allMovies.forEach((r) => {
            if (r.id === row.id) {
              this.$refs.multipleTable.toggleRowSelection(r,true);
            }
          });
        });
      });
      }
      
    },
    // 表单提交
    dataFormSubmit() {
      console.log()
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/user/${!this.dataForm.userId ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              userId: this.dataForm.userId || undefined,
              username: this.dataForm.username,
              password: this.dataForm.password,
              salt: this.dataForm.salt,
              email: this.dataForm.email,
              mobile: this.dataForm.mobile,
              status: this.dataForm.status,
              address: this.dataForm.address,
              specificAddr: this.dataForm.specificAddr,
              endorse: this.dataForm.endorse,
              allowRefund: this.dataForm.allowRefund,
              hallType: this.dataForm.hallType,
              snack: this.dataForm.snack,
              movies: this.dataForm.movies,
              realName: this.dataForm.realName,
              roleIdList: [2],
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
};
</script>
